import 'dart:io';

import 'package:dio/dio.dart' as http;
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:install_plugin_custom/install_plugin_custom.dart';
import '../net/dio_utils.dart';
///代码清单12-8 首页面使用控制器
///lib/controller/home_controller.dart
class HomeController extends GetxController {
  //首页面主体使用的滑动控制器
  final PageController pageController = PageController();

  int currentIndex = 0;
  List<IconData> normalImgUrls = [
    Icons.home,
    Icons.menu,
    Icons.menu_book_rounded,
    Icons.people,
  ];
  List<IconData> selectedImgUrls = [
    Icons.home,
    Icons.menu,
    Icons.menu_book_rounded,
    Icons.people,
  ];


  List<String> titles = ["首页", "分类", "阅读", "我的"];

  void onBottomTap(int index) {
    if (currentIndex != index) {
      currentIndex = index;
      pageController.jumpToPage(currentIndex);
      update();
    }
  }

  @override
  void onReady() {
    super.onReady();
    //加载请求版本信息

    //如果有新版本
    if (Platform.isAndroid) {
      downAndInstall();
    } else {
      InstallPluginCustom.gotoAppStore("应用在AppStore地址");
    }
  }
  ///代码清单12-8-1 下载APK
  void downAndInstall() async {
    //apk 网络存储链接
    String apkNetUrl = "";
    //手机中sd卡上 apk 下载存储路径
    String localPath = "";

    http.Dio dio = http.Dio();
    //设置连接超时时间
    dio.options.connectTimeout = 1200000;
    //设置数据接收超时时间
    dio.options.receiveTimeout = 1200000;
    http.Response response = await dio.download(apkNetUrl, localPath,
        onReceiveProgress: (int count, int total) {
      // count 当前已下载文件大小
      // total 需要下载文件的总大小
    });
    if (response.statusCode == 200) {
      print('下载请求成功');
      //"安装";
      InstallPluginCustom.installApk(
        localPath,
        '应用包名',
      ).then((result) {
        print('install apk $result');
      }).catchError((error) {
        print('install apk $error');
        //安装失败
      });
    } else {
      //"下载失败重试";
    }
  }
}
